#!/usr/bin/env bash
# @sys: centos-stream-8
# @date: Mon Jun 27 09:27:42 CST 2022
# @author: yangfan
# @email: yangfan@moonpac.com
# @info: bak mysql data
# @run: ./bak_mysql_data.sh


# vars
time=`date +%Y%m%d`
bak_path=/mnt/bak_mysql_data/${time}
host_address=127.0.0.1
username=${1}
password=${2}
db_name=${3}
table_name=''

if [ ! -n "${1}" ] ;then
    echo -e "\033[31m Please enter parameter mysql username --------> fail\033[0m"; exit 1;
fi

if [ ! -n "${2}" ] ;then
    echo -e "\033[31m Please enter parameter mysql password --------> fail\033[0m"; exit 1;
fi

if [ ! -n "${3}" ] ;then
    echo -e "\033[31m Please enter parameter db_name --------> fail\033[0m"; exit 1;
fi

if [ ! -n "${4}" ] ;then
    echo -e "\033[32m default parameter bak_path (${bak_path})\033[0m";
    mkdir -p ${bak_path}
else
    bak_path=${4}/bak_mysql_data/${time}
    mkdir -p ${bak_path}
fi

if [ ! -n "${5}" ] ;then
    echo -e "\033[32m default parameter host_address (127.0.0.1)\033[0m";
else
    host_address=${5}
fi

if [ ! -n "${6}" ] ;then
    echo -e "\033[32m default parameter table_name (null)\033[0m";
else
    table_name=${6}
fi



function check() {
    if [[ $? == 0 ]]; then
        echo -e "\033[32m${1} --------> success\033[0m";
    else
        echo -e "\033[31m${1} --------> fail\033[0m"; exit 1;
    fi
}



# if the program exists
/usr/bin/which mysqldump &>/dev/null || (echo -e "\033[31mbash: mysqldump: command not found...\033[0m"; exit 1;)
cmd=`/usr/bin/which mysqldump`


# bak database
function bakDatabase() {
    if [[ ! -n ${table_name} ]]; then
        bak_name=${db_name}.sql
    else
        bak_name=${db_name}_${table_name}.sql
    fi

    ${cmd} -u${username} -p${password} -h${host_address} \
    --add-drop-table \
    ${db_name} \
    ${table_name} > "${bak_path}/${bak_name}"

    check "mysql database bakup"

    cd ${bak_path} && cd ..
    tar zcfP bak-mysql-data-${db_name}-${time}.tar.gz ${time}
    rm -rf ${time}
    check "bak path `pwd`"
}

bakDatabase
